﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Metadata.Edm;
using System.Collections;
using System.Globalization;
using System.Runtime;

namespace MetadataBasedConfig.EntityModel.Entity
{
    public class BasicObjectSet<TEntity> : ObjectQuery<TEntity>, IObjectSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable
        where TEntity : class
    {    
        private readonly EntitySet _entitySet;

        internal BasicObjectSet(EntitySet entitySet, ObjectContext context)
            : base("", context, MergeOption.AppendOnly)
        {
            this._entitySet = entitySet;
        }


        public void AddObject(TEntity entity)
        {
            base.Context.AddObject(this.FullyQualifiedEntitySetName, entity);
        }

        public TEntity ApplyCurrentValues(TEntity currentEntity)
        {
            return base.Context.ApplyCurrentValues<TEntity>(this.FullyQualifiedEntitySetName, currentEntity);
        }

        public TEntity ApplyOriginalValues(TEntity originalEntity)
        {
            return base.Context.ApplyOriginalValues<TEntity>(this.FullyQualifiedEntitySetName, originalEntity);
        }

        public void Attach(TEntity entity)
        {
            base.Context.AttachTo(this.FullyQualifiedEntitySetName, entity);
        }

        public T CreateObject<T>() where T : class, TEntity
        {
            return base.Context.CreateObject<T>();
        }

        public TEntity CreateObject()
        {
            return base.Context.CreateObject<TEntity>();
        }

        public void DeleteObject(TEntity entity)
        {
            //base.Context.DeleteObject(entity, this.EntitySet);
        }

        public void Detach(TEntity entity)
        {
            //base.Context.Detach(entity, this.EntitySet);
        }

        public EntitySet EntitySet
        {
            [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
            get
            {
                return this._entitySet;
            }
        }

        private string FullyQualifiedEntitySetName
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { this._entitySet.EntityContainer.Name, this._entitySet.Name });
            }
        }

    }
}
